﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Globalization;

namespace MailQueueUmbracoAdmin
{
    public partial class MailQueueStatistics : System.Web.UI.UserControl
    {
        private string[] statusLabels = new string[] { "Spool", "Sent", "Warning", "Error" };
        private string[] timeLabels = new string[] { "Last 24 Hours", "Last Week", "Last Month", "For Ever" };

        protected void Page_Load(object sender, EventArgs e)
        {
            statisticImages.Text = LoopThroughLabels();
        }

        protected string LoopThroughLabels()
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            sb.Append(LoopThroughTimes(null));

            string sqlCmdText = "SELECT DISTINCT Label FROM MailQueue ORDER BY LABEL DESC";

            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = sqlCmdText;
            cmd.CommandType = System.Data.CommandType.Text;
            SqlDataReader dr = DbHelper.DbHelper.ExecuteSqlReader(cmd, System.Configuration.ConfigurationManager.ConnectionStrings["mailqueue"].ConnectionString);

            using (dr)
            {
                while (dr.Read())
                {
                    string lbl = String.Empty;
                    if (dr.IsDBNull(0))
                        lbl = String.Empty;
                    else
                        lbl = dr.GetString(0);

                    sb.Append(LoopThroughTimes(lbl));
                }
            }

            dr.Close();

            return sb.ToString();
        }

        protected string LoopThroughTimes(string Label)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            string chartLabel = Label;

            if (Label != null && Label.Equals(String.Empty))
                chartLabel = "[No label]";
            else if (Label == null)
                chartLabel = "All";

            sb.Append("<DIV><FIELDSET><LEGEND>");
            sb.Append(chartLabel);
            sb.Append("</LEGEND>");

            DateTime[] times = new DateTime[4];
            times[0] = DateTime.Now.AddHours(-24);
            times[1] = DateTime.Now.AddDays(-7);
            times[2] = DateTime.Now.AddMonths(-1);
            times[3] = DateTime.MinValue;

            for (int i = 0; i < times.Length; i++)
            {
                sb.Append("<IMG SRC=\"");
                sb.Append(GetImageUrlForGoogleChart("p3", "300x100", Label, timeLabels[i], times[i]));
                sb.Append("\" />");
            }

            sb.Append("</FIELDSET><DIV>");

            return sb.ToString();

        }

        protected string GetImageUrlForGoogleChart(string ChartType, string ChartSize, string Label, string ChartTitle, DateTime FromDate)
        {

            string sqlCmdText = "select [MailStatus], count(MailStatus) as Cnt FROM [MailQueue]";

            if (FromDate != DateTime.MinValue && Label != null)
                sqlCmdText += " WHERE MailCreateTime > @created AND Label = @label";

            else if (FromDate != DateTime.MinValue && Label == null)
                sqlCmdText += " WHERE MailCreateTime > @created";

            else if (FromDate == DateTime.MinValue && Label != null)
                sqlCmdText += " WHERE Label = @label";

            sqlCmdText += " GROUP BY [MailStatus]";

            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = sqlCmdText;
            cmd.CommandType = System.Data.CommandType.Text;


            if (FromDate != DateTime.MinValue && Label != null)
            {
                cmd.Parameters.AddWithValue("@created", FromDate);
                cmd.Parameters.AddWithValue("@label", Label);
            }

            else if (FromDate != DateTime.MinValue && Label == null)
            {
                cmd.Parameters.AddWithValue("@created", FromDate);
            }

            else if (FromDate == DateTime.MinValue && Label != null)
            {
                cmd.Parameters.AddWithValue("@label", Label);
            }

            SqlDataReader dr = DbHelper.DbHelper.ExecuteSqlReader(cmd, System.Configuration.ConfigurationManager.ConnectionStrings["mailqueue"].ConnectionString);

            double[] statusCount = new double[] { 0, 0, 0, 0 };
            double totalCount = 0;

            using (dr)
            {
                while (dr.Read())
                {
                    int mailStatus = (int)dr["MailStatus"];
                    double mailCount = Convert.ToDouble((int)dr["Cnt"]);

                    totalCount += mailCount;

                    switch (mailStatus)
                    {
                        case 1:
                            statusCount[0] = mailCount;
                            break;
                        case 2:
                            statusCount[1] = mailCount;
                            break;
                        case 4:
                            statusCount[2] = mailCount;
                            break;
                        case 8:
                            statusCount[3] = mailCount;
                            break;
                    }
                }
            }

            dr.Close();

            string chd = String.Empty;
            string chl = String.Empty;
            string chco = "4682b4,66cdaa,ffffa0,ff3600";

            if (totalCount > 0)
            {
                for (int i = 0; i < statusCount.Length; i++)
                {
                    double d = (statusCount[i] / totalCount) * 100;
                    string percentage = d.ToString("0.00", CultureInfo.InvariantCulture);
                    chd += percentage + ",";

                    string stCntStr = statusCount[i]==0 ? "0" : statusCount[i].ToString("#,#", CultureInfo.InvariantCulture);
                    string lbl = statusLabels[i] + " (" + stCntStr + ")";
                    chl += lbl + "|";
                }

                chd = chd.Substring(0, chd.Length - 1);
                chl = chl.Substring(0, chl.Length - 1);
            }
            else
            {
                chd = "100";
                chl = "Nothing";
                chco = "EEEEEE";
            }

            string chartUrl = @"http://chart.apis.google.com/chart?cht={0}&chd=t:{1}&chs={2}&chl={3}&chtt={4}&chco={5}";
            return String.Format(chartUrl, ChartType, chd, ChartSize, chl, ChartTitle, chco);
        }
    }
}